import redisdb from '../config/redisdb';
import co from 'co';
import md5 from 'md5';

import { model as DeviceMsgAudit } from '../models/deviceMsgAudit';
import { model as ClientMsg } from '../models/clientMsg';

const device2active = 'active';


class Receiver {
    constructor(app) {
        this.app = app;

        this.log = app.log.getLogger('handle');
    }

    onMessage(message) {
        const msg = message || {};

        const msgType = 'type' in msg ? msg.type : null;

        if (!msgType || !(msgType in this)) {
            this.log.error('[receiver_onMessage] not found match message = %s', message);
            return;
        }
        co(this[msgType].bind(this, msg));
    }

    * active(_data) {
        this.log.info('[active] _data: %s', JSON.stringify(_data));
        const data = _data.data;

        const sys = data.sys;
        const wid = data.wid;

        // 获取 client
        const client = this.app.getClient(data.deviceId);
        if (!client) {
            this.log.error('[active] ws connect not found: deviceId = %s, wid = %s, uid = %s',
                data.deviceId, wid, data.uid);
            return;
        }

        // token 秘钥
        const tokenKey = Math.random().toString(36).substr(2, 6);
        const token = md5(`${data.deviceId}-${tokenKey}`);

        client.send('dc:active', { status: 200, token }, client.id);

        this.log.info('[active] success: deviceId = %s, sys = %s, wid = %s',
            data.deviceId, sys, wid);
    }

    * message(_data) {
        const sys = _data.sys;
        const wid = _data.wid;

        this.log.info('[message] _data: %s', JSON.stringify(_data));

        // conn redis[device] 9
        const redisDevice = this.app.redis(redisdb.device);
        const devices = yield redisDevice.hgetall(`${device2active}:${sys}:${wid}`);

        if (!devices || Object.keys(devices).length === 0) {
            this.log.warn('[message] sys: %s, wid: %s not exist active device', sys, wid);
            return;
        }
    }

    * clientTest(_data) {
        this.log.info('[client_test] _data: %s', JSON.stringify(_data));

        const sys = _data.sys;
        const wid = _data.wid;
        const tableId = _data.tableId;
        const openId = _data.openId;
        const tableNo = _data.tableNo;

        const sql = `
            select code from km_code where wid = ?;
        `;

        const res = yield this.app.mysql.execute(sql, [wid]);
        const serialId = res[0].code;


        new ClientMsg({
            serialId,
            param: {
                sys,
                wid,
                tableId,
                tableNo,
                openId,
            },
            data: {
                cmd: 'ZDCX',
                tableNo,
            },
        }).save();
    }

    saveMsgAudit(deviceId, state, data, memo) {
        new DeviceMsgAudit({
            deviceId,
            state,
            data: typeof data === 'object' ? JSON.stringify(data) : data,
            memo,
        }).save();
    }
}

export default Receiver;
